﻿using Microsoft.Extensions.DependencyInjection;
using MyCommon.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyExtension.ServiceExtensions
{
    /// <summary>
    /// 注入 SQLSugar 服务
    /// </summary>
    public static class SqlSugarSetup
    {
        /// <summary>
        ///  注入 SQLSugar 服务
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddSqlSugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            
            // 数据库连接字符串
            var conn = Appsettings.app(new string[] { "ConnectionString" });
            var dbType = Appsettings.app(new string[] { "DbType" });
            
            // 以单例方式注入 ISqlSugarClient 服务 
            services.AddSingleton<ISqlSugarClient>(s =>
            {
                return new SqlSugarScope(
                    new ConnectionConfig() {
                        DbType = (DbType)int.Parse( dbType),
                        // DbType.MySql,
                        ConnectionString = conn,
                        IsAutoCloseConnection = true,
                        ConfigureExternalServices = new ConfigureExternalServices
                        {
                            EntityService = (p, c) =>
                            {
                                if (c.IsPrimarykey == false && new NullabilityInfoContext().Create(p).WriteState is NullabilityState.Nullable)
                                {
                                    c.IsNullable = true;
                                }
                            },
                            EntityNameService = (p, c) =>
                            {
                                // c.DbTableName = UtilMethods.ToUnderLine(c.DbTableName);
                            }
                        }
                    },db =>
                     {
                         //单例参数配置，所有上下文生效
                         db.Aop.OnLogExecuting = (s, p) =>
                         {
                             Console.WriteLine(UtilMethods.GetNativeSql(s, p));
                         };
                     });
            });
        }
    }

}
